package com.hsq.ndmall.auth.service;

import cn.hutool.core.map.MapUtil;
import com.hsq.ndmall.auth.dto.ClientDto;
import com.hsq.ndmall.auth.feign.AdminFeign;
import com.hsq.ndmall.common.utils.ListFromEntity2VoUtils;
import com.hsq.ndmall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 黄四清
 * @version 1.0.0
 * @ClassName ClientDetailsServiceImpl.java
 * @Description TODO
 * @createTime 2021年08月26日 19:41:00
 */
@Service
public class ClientDetailsServiceImpl implements ClientDetailsService {
    @Autowired
    AdminFeign adminFeign;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public ClientDetails loadClientByClientId(String s) throws ClientRegistrationException {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("client",s);
        R clientDetailR  = adminFeign.list(paramMap);
        List<Map> clientDetailListMap = MapUtil.get((Map) clientDetailR.get("page"), "list", List.class);
        List<ClientDto> clientDtoList = ListFromEntity2VoUtils.entity2Vo(clientDetailListMap, ClientDto.class);

        if (clientDtoList != null || clientDtoList.size() > 0) {
            ClientDto clientDto = clientDtoList.get(0);
            BaseClientDetails clientDetails = new BaseClientDetails(
                    clientDto.getClientId(),
                    clientDto.getResourceIds(),
                    clientDto.getScope(),
                    clientDto.getAuthorizedGrantTypes(),
                    clientDto.getAuthorities(),
                    clientDto.getWebServerRedirectUri()
                    //clientDto.getAccessTokenValidity().toString()
            );
            System.out.println("------------------------------------执行到这了-----------------");
            clientDetails.setClientSecret(passwordEncoder.encode(clientDto.getClientSecret()));
            clientDetails.setAccessTokenValiditySeconds(clientDto.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(clientDto.getRefreshTokenValidity());
            return clientDetails;
        } else {
            throw new NoSuchClientException("No client with requested id: " + s);
        }
    }
}
